package service

import (
	"gin-vue-admin/global"
	"gin-vue-admin/model"
	"gin-vue-admin/model/request"
)

//@author: [piexlmax](https://github.com/piexlmax)
//@function: CreateTails
//@description: 创建Tails记录
//@param: tails model.Tails
//@return: err error

func CreateTails(tails model.Tails) (err error) {
	err = global.GVA_DB.Create(&tails).Error
	return err
}

//@author: [piexlmax](https://github.com/piexlmax)
//@function: DeleteTails
//@description: 删除Tails记录
//@param: tails model.Tails
//@return: err error

func DeleteTails(tails model.Tails) (err error) {
	err = global.GVA_DB.Delete(&tails).Error
	return err
}

//@author: [piexlmax](https://github.com/piexlmax)
//@function: DeleteTailsByIds
//@description: 批量删除Tails记录
//@param: ids request.IdsReq
//@return: err error

func DeleteTailsByIds(ids request.IdsReq) (err error) {
	err = global.GVA_DB.Delete(&[]model.Tails{},"id in ?",ids.Ids).Error
	return err
}

//@author: [piexlmax](https://github.com/piexlmax)
//@function: UpdateTails
//@description: 更新Tails记录
//@param: tails *model.Tails
//@return: err error

func UpdateTails(tails model.Tails) (err error) {
	err = global.GVA_DB.Save(&tails).Error
	return err
}

//@author: [piexlmax](https://github.com/piexlmax)
//@function: GetTails
//@description: 根据id获取Tails记录
//@param: id uint
//@return: err error, tails model.Tails

func GetTails(id uint) (err error, tails model.Tails) {
	err = global.GVA_DB.Where("id = ?", id).First(&tails).Error
	return
}

//@author: [piexlmax](https://github.com/piexlmax)
//@function: GetTailsInfoList
//@description: 分页获取Tails记录
//@param: info request.TailsSearch
//@return: err error, list interface{}, total int64

func GetTailsInfoList(info request.TailsSearch) (err error, list interface{}, total int64) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
    // 创建db
	db := global.GVA_DB.Model(&model.Tails{})
    var tailss []model.Tails
    // 如果有条件搜索 下方会自动创建搜索语句
    if info.Station != "" {
        db = db.Where("`station` LIKE ?","%"+ info.Station+"%")
    }
    if info.StepTime != "" {
        db = db.Where("`step_time` LIKE ?","%"+ info.StepTime+"%")
    }
	err = db.Count(&total).Error
	err = db.Limit(limit).Offset(offset).Find(&tailss).Error
	return err, tailss, total
}

// 根据LineId查询数据列表
func GetTailsListByLineId(info request.TailsSearch) (err error, list interface{}, total int64) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	// 创建db
	db := global.GVA_DB.Model(&model.Tails{})
	var tailss []model.Tails
	db = db.Where("`lines_id` = ?",info.LinesId)
	err = db.Count(&total).Error
	err = db.Limit(limit).Offset(offset).Find(&tailss).Error
	return err, tailss, total
}


// 根据LineId的最大创建时间查询最新记录
func GetTailsByMaxCreateTimeWhereLineId(LineId uint) (err error, tails model.Tails) {
	err = global.GVA_DB.Where("tails.created_at = (select max(created_at) from tails where tails.lines_id = ?)", LineId).First(&tails).Error
	return
}